import { TipsKindEnum } from "../enum";
import type { TipsType } from "../types";
import { createElement } from "../createElement";

/**
 * @example 创建的dom元素
 * `
    <div class="tips" level="0">
        <div class="tips1"></div>
        <div class="tips2"></div>
    </div>
    `
 * @returns tips组件对象，继承了HTMLElement接口
 */
export function initTips(): HTMLElement & TipsType {
    let tipsKind: TipsKindEnum = 0;
    let priorTipsTimmer: NodeJS.Timeout;
    let normalTipsTimmer: NodeJS.Timeout;
    const tipsEle = createElement('div', { class: 'tips', level: String(tipsKind)});
    const priorTipsEle = createElement('div', { class: 'tips1' });
    const normalTipsEle = createElement('div', { class: 'tips2' });
    tipsEle.appendChild(priorTipsEle);
    tipsEle.appendChild(normalTipsEle);

    let appenFn: TipsType = {
        show(kind: TipsKindEnum, content: string | number) {
            if(!this.isMounted()) return;
            // tipsKind重置为零
            if ( tipsKind !== TipsKindEnum.cartion || kind === TipsKindEnum.none ) {
                const mius = kind - tipsKind;
                tipsKind = kind;
                priorTipsEle.style.width = '0';
                priorTipsEle.style.opacity = '0';
                priorTipsEle.innerHTML = String(content);
                tipsEle.setAttribute('level', String(kind))
                if (kind !== 0) {
                    priorTipsTimmer && clearTimeout(priorTipsTimmer);
                    priorTipsTimmer = setTimeout(() => {
                        tipsEle.setAttribute('level', String(kind))
                        priorTipsEle.style.width = '9.5rem';
                        priorTipsEle.style.opacity = '0.8';
                    }, mius * 300)
                }
                return;
            }
            normalTipsEle.innerHTML = String(content);
            normalTipsEle.style.width = '9.5rem';
            normalTipsTimmer && clearTimeout(normalTipsTimmer);
            normalTipsTimmer = setTimeout(() => {
                normalTipsEle.style.width = '0';
            }, 1800)

        },
        hide() {
            priorTipsTimmer && clearTimeout(priorTipsTimmer);
            normalTipsTimmer && clearTimeout(normalTipsTimmer);
            this.show(TipsKindEnum.none, '');
        },
        isMounted():boolean {
            return Boolean(tipsEle.parentElement);
        },
    }

    return Object.assign(tipsEle, appenFn);
}